<template>
  <div id="app">
    <div class="input-section">
      <el-input
        placeholder="输入问题"
        v-model="question"
        clearable>
      </el-input>
    </div>
    <div class="button-section">
      <el-button type="primary" @click="submitQuestion">提交问题</el-button>
    </div>
    <div class="output-section">
      <el-input
        type="textarea"
        :rows="16"
      placeholder="回答内容"
      v-model="answer"
      readonly>
      </el-input>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      question: "",
      answer: "",
      loadingInstance: null // 用于控制加载动画的实例
    }
  },
  methods: {
    submitQuestion() {
      if (this.question.length === 0) {
        this.$message({
          type: 'error',
          message: '问题不能为空',
        });
      } else {
        // 启动加载动画
        this.loadingInstance = this.$loading({
          lock: true,
          text: '正在获取答案...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        // 将问题发送到后端
        axios.post('http://localhost:8080/api/ask', { question: this.question })
          .then(res => {
            if (res.data.code === 200) {
              // 将后端返回的回答填充到 answer 文本框
              this.answer = res.data.answer;
              this.$message({
                type: "success",
                message: "正在出题"
              });

            } else {
              this.$message({
                type: "error",
                message: "提交失败，请重试"
              });
            }
          })
          .catch(error => {
            this.$message({
              type: "error",
              message: "请求失败，请重试"
            });
          })
          .finally(() => {
            // 关闭加载动画
            this.loadingInstance.close();
          });
      }
    }
  }
}
</script>

<style scoped>
.input-section, .button-section, .output-section {
  margin: 20px 0;
}
</style>
